package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import cn.edu.swu.miniwebsvr.handler.EchoHandler;
import cn.edu.swu.miniwebsvr.handler.TimeHandler;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Config {
    private final int port = 8080;
    private final String webRoot = "webroot";
    private final Map<String, Handler> handlerMap = new HashMap<>();

    private Config() {
        handlerMap.put("/", new DefaultHandler());
        handlerMap.put("/time", new TimeHandler());
        handlerMap.put("/echo", new EchoHandler());
    }

    public static Config getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final Config INSTANCE = new Config();
    }

    public int getPort() {
        return port;
    }

    public String getWebRoot() {
        return webRoot;
    }

    public Handler getHandler(String url) {
        // TODO: [222024321072010/黄天灿] 实现 URL 精确匹配或基础路径匹配逻辑
        if (url == null || url.isEmpty()) {
            return handlerMap.get("/");
        }

        Handler exact = handlerMap.get(url);
        if (exact != null) {
            return exact;
        }

        String cur = url;
        while (true) {
            int idx = cur.lastIndexOf('/');
            if (idx <= 0) {
                break;
            }
            cur = cur.substring(0, idx);
            Handler h = handlerMap.get(cur);
            if (h != null) {
                return h;
            }
        }

        return handlerMap.get("/");
    }
}